package com.hmdp.service.impl;

import com.hmdp.dto.Result;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.UserHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    /**
     * 秒杀优惠卷service
     */
    @Resource
    private ISeckillVoucherService seckillVoucherService;

    @Resource
    private RedisIdWorker redisIdWorker;




    /**
     * 优惠卷订单信息
     * @param voucherId 优惠卷id
     * @return
     */
    @Override
    @Transactional
    public Result seckillVoucher(Long voucherId) {

        //判断参数是否符合
        if (voucherId == null) {
            throw new RuntimeException("voucherId参数不符合!:"+voucherId);
        }

        //查询优惠卷信息
        SeckillVoucher seckillVoucher = seckillVoucherService.getById(voucherId);

        //判断秒杀是否开始
        //秒杀开始时间在当前时间之后,表示秒杀没有开始
        if (seckillVoucher.getBeginTime().isAfter(LocalDateTime.now())) {
            //秒杀没有开始
            return Result.fail("秒杀没有开始!");
        }
        //判断秒杀是否结束
        //秒杀结束时间在当前时间之前,表示秒杀结束
        if (seckillVoucher.getEndTime().isBefore(LocalDateTime.now())) {
            //秒杀结束
            return Result.fail("秒杀已经结束!");
        }
        //判断是否库存是否充足
        if (seckillVoucher.getStock() < 1) {
            //库存不足
            return Result.fail("库存不足!");
        }

        //扣减库存
        boolean success = seckillVoucherService.update().setSql("stock = stock - 1")
                                                .eq("voucher_id", voucherId).update();
        //false
        if (!success){
            //扣减失败
            return Result.fail("库存不足,扣减失败!");
        }

        //创建订单信息
        VoucherOrder voucherOrder = new VoucherOrder();
        //订单id
        long orderId = redisIdWorker.nextId("order");
        voucherOrder.setId(orderId);
        //用户id
        Long id = UserHolder.getUser().getId();
        voucherOrder.setUserId(id);
        //代金卷id
        voucherOrder.setVoucherId(voucherId);

        //写入数据库
        save(voucherOrder);

        //返回订单id
        return Result.ok(orderId);
    }
}
